//
//  NetWorkTools.swift
//  DragonPlatform
//
//  Created by JF.Zhan on 2017/9/27.
//  Copyright © 2017年 JF.Zhan. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import Foundation

// 请求响应状态
// - success: 响应成功
// - unusual: 响应异常
// - failure: 请求错误

enum ResponseStatus: Int {
    
    case success    = 0
    case unusual    = 1
    case failure    = 2
}

// 网络请求回调闭包 status：响应状态 result：JSON tipString：提示给用户的信息
typealias NetworkFinihsed = (_ status : ResponseStatus, _ result : JSON?, _ tipString : String) -> ()

class NetWorkTools: Alamofire.SessionManager {
    
    // 网络工具单例
    
    private static let tool : NetWorkTools = {
        
        let configuration = URLSessionConfiguration.default
        
        return NetWorkTools(configuration: configuration)
    }()
    
    class func shareNetworkTool() -> NetWorkTools {
        
        return tool
    }
    
}

// MARK: - 基础请求方法
extension NetWorkTools {
    
    /**
     GET请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func get(_ APIString : String, parameters : [String : Any]? , needLoading : Bool, finished : @escaping NetworkFinihsed) {
        
        if needLoading {
            
            CommonMethod.shared.showProgressHUDWithTitle(title: "正在加载", superView: UIApplication.shared.keyWindow!, animated: true)
        }
        
        request(APIString, method: .get, parameters:parameters).responseJSON { (response) in
            
            self.complectionHandler(response: response, finished: finished, needLoading: needLoading)
        }
    }
    
    /**
     POST请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func post(_ APIString : String, parameters : [String : Any]?, needLoading : Bool, finished : @escaping NetworkFinihsed) {
        
        if needLoading {
            
//            CommonMethod.shared.showProgressHUDWithTitle(title: "正在加载", superView: UIApplication.shared.keyWindow!, animated: true)
        }
        
        request(APIString, method:.post, parameters:parameters).responseJSON { (response) in
            
            self.complectionHandler(response: response, finished: finished, needLoading: needLoading)
        }
        //可以替换
        //        request(APIString, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
        //            self.complectionHandler(response: response, finished: finished, needLoading: needLoading)
        //        }
    }
    
    /**
     上传图片请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func upload(_ APIString: String, image: UIImage ,parameters: [String : Any]?, needLoading: Bool,finished: @escaping NetworkFinihsed) {
        
        
        if needLoading {
            
//            CommonMethod.shared.showProgressHUDWithTitle(title: "正在上传", superView: UIApplication.shared.keyWindow!, animated: true)
        }
        
        upload(
            multipartFormData: { multipartFormData in
                
                //                let imageData = UIImageJPEGRepresentation(image, 0.3);
                let imageData = image.jpegData(compressionQuality: 0.3)
                let imageName = ""//CommonMethod.shared.curTimeWithFormat()+".jpg"
                
                
                if imageData != nil {
                    
                    multipartFormData.append(imageData!, withName: "yh_tx", fileName: imageName, mimeType: "multipart/form-data")
                    
                    for (key, value) in parameters! {
                        
                        multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
                        
                    }
                }
                
                //                print(multipartFormData)
        },
            to: APIString,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { (response) in
                        
                        self.complectionHandler(response: response, finished: finished, needLoading: needLoading)
                        
                    }
                case .failure(let encodingError):
                    
//                    CommonMethod.shared.hideProgressHUDInView(superView: UIApplication.shared.keyWindow!, animated: true)
                }
                
        })
    }
    
    /**
     上传证件图片请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func uploadCredentials(_ APIString: String, image: UIImage ,parameters: [String : Any]?, needLoading: Bool,finished: @escaping NetworkFinihsed) {
        
        
        if needLoading {
            
//            CommonMethod.shared.showProgressHUDWithTitle(title: "正在上传", superView: UIApplication.shared.keyWindow!, animated: true)
        }
        
        upload(
            multipartFormData: { multipartFormData in
                
                //                let imageData = UIImageJPEGRepresentation(image, 0.3);
                let imageData = image.jpegData(compressionQuality: 0.3)
                let imageName = ""//CommonMethod.shared.curTimeWithFormat()+".jpg"
                
                
                if imageData != nil {
                    
                    multipartFormData.append(imageData!, withName: "file", fileName: imageName, mimeType: "multipart/form-data")
                    
                    for (key, value) in parameters! {
                        
                        multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
                        
                    }
                }
                
        },
            to: APIString,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { (response) in
                        
                        self.complectionHandler(response: response, finished: finished, needLoading: needLoading)
                        
                    }
                case .failure(let encodingError):
                    
//                    CommonMethod.shared.hideProgressHUDInView(superView: UIApplication.shared.keyWindow!, animated: true)
                }
                
        })
    }
    
    
    /// 处理响应结果
    ///
    ///   - response: 响应对象
    ///   - finished: 完成回调
    fileprivate func complectionHandler(response: DataResponse<Any>, finished: @escaping NetworkFinihsed, needLoading: Bool) {
        
        if needLoading {
            
//            CommonMethod.shared.hideProgressHUDInView(superView: UIApplication.shared.keyWindow!, animated: true)
        }
        
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            
            if let code = json["returnData"]["head"]["code"].string {
                
                if code.isEqual("00") {
                    
                    finished(.success, json["returnData"]["body"], json["returnData"]["head"]["msg"].string!)
                    
                } else {
                    
                    if let code = json["returnCode"].string {
                        if code.isEqual("02") {
                            
                        }
                    }
                    
                    finished(.failure, json["returnData"]["body"], json["returnData"]["head"]["msg"].string!)
                    
                    if (response.request?.url?.absoluteString.contains("appLoginCtl/applogin"))! {
                        
                    } else {
                        if json["returnData"]["head"]["msg"].string!.contains("登录") && !json["returnData"]["head"]["msg"].string!.contains("登录成功") && !json["returnData"]["head"]["msg"].string!.contains("用户已经登录") || json["returnData"]["head"]["msg"].string!.contains("onli") {
                            if !(response.request?.url?.absoluteString.contains("appOrgCtl/getMrdp"))! {
//                                let loginVC = LoginVC()
//                                loginVC.hidesBottomBarWhenPushed = true
//
//                                let nav = BaseNavigationController.init(rootViewController: loginVC)
//                                UIApplication.shared.keyWindow?.rootViewController = nav
                                
                                return
                            }
                            
                        } else {
//                            CommonMethod.shared.createCommonAlertView(title: "", message: json["returnData"]["head"]["msg"].string!, time: 1.0)
                        }
                        
                    }
                    
                    
                }
            }
            
            if let code = json["returnCode"].string {
                
                if code.isEqual("00")  {
                    
                    finished(.success, json["body"], "成功")
                    
                } else {
                    
                    var message = String()
                    
                    if let mess = json["returnMsg"].string {
                        message = mess
                    }
                    
                    if message.contains("登录") && !message.contains("登录成功") && !message.contains("用户已经登录") || message.contains("onli") {
                        if !(response.request?.url?.absoluteString.contains("appOrgCtl/getMrdp"))! {
//                            let loginVC = LoginVC()
//                            loginVC.hidesBottomBarWhenPushed = true
//
//                            let nav = BaseNavigationController.init(rootViewController: loginVC)
//                            UIApplication.shared.keyWindow?.rootViewController = nav
//                            return
                        }
                    }
                    
                    if (response.request?.url?.absoluteString.contains("appXxCtl/xxIndex"))! || (response.request?.url?.absoluteString.contains("appGwcCtl/gwcInfo"))! ||  (response.request?.url?.absoluteString.contains("appOrgCtl/orgInfo"))! {
                        
                        if let code = json["returnCode"].string {
                            if code.isEqual("02") {
                                
                            }
                        }
                        
                    } else {
                        
                        
                        finished(.failure, json["body"], message)
                    }
                    
                    
                    if ((response.request?.url?.absoluteString.contains("appQdCtl/commitQd"))!) {
                        
                        var returnMessage = String()
                        
                        if code.isEqual("04") {
                            returnMessage = "抢单失效"
                        } else if code.isEqual("05") {
                            returnMessage = "抢单被其他商家抢单"
                        } else if code.isEqual("06") {
                            returnMessage = "商家店铺无商品"
                        } else if code.isEqual("07") {
                            returnMessage = "商家店铺中无一种或多种商品"
                        } else if code.isEqual("08") {
                            returnMessage = "商家店铺的某一种商品库存量不足"
                        } else if code.isEqual("01") {
                            returnMessage = "抢单失败"
                        }
//                        CommonMethod.shared.createCommonAlertView(title: "", message: returnMessage, time: 1.0)
                        
                    }else {
                        
                        if message.contains("登录") || message.contains("onli") {} else {
//                            CommonMethod.shared.createCommonAlertView(title: "", message: message, time: 1.0)
                        }
                        
                    }
                }
            }
            
            
            
        case .failure(let error):
            
//            CommonMethod.shared.networkBadBack()
            
            finished(.failure, nil, error.localizedDescription)
            
        }
    }
}
